package com.lizi.core.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.Collection;
import java.util.Iterator;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串相关的工具类
 * Created by lixy on 15-1-4.
 */
public class StringUtils {

    // 国标码和区位码转换常量
    static final int GB_SP_DIFF = 160;

    // 存放国标一级汉字不同读音的起始区位码
    static final int[] secPosvalueList = { 1601, 1637, 1833, 2078, 2274, 2302,
            2433, 2594, 2787, 3106, 3212, 3472, 3635, 3722, 3730, 3858, 4027,
            4086, 4390, 4558, 4684, 4925, 5249, 5600 };

    // 存放国标一级汉字不同读音的起始区位码对应读音
    static final char[] firstLetter = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
            'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'w', 'x',
            'y', 'z' };

    /** 姓 */
    private static final String[] firstName = new String[]{"zhao","qian","sun","li","zhou","wang"
            ,"wu","zheng","feng","chen","chu","wei","jiang","shen","yang","zhu","qin","you","xu","he"
            ,"shi","zhan","kong","cao","xie","jin","shu","fang","yuan"};

    /** 电话号码前缀 */
    private static final String[] telHead = new String[]{"139","138","137","159","152","151","150"
            ,"188","187","130","132"};

    /** 邮箱后缀 */
    private static final String[] emailSuffix = new String[]{"@lizi.com","@qq.com","@163.com"
            ,"@sina.com","@qihoo.com"};

    private static int max = Integer.MAX_VALUE;


    /**
     * 判断字符串是否不为空
     * @param str
     * @return
     */
    public static boolean isNotEmpty(String str) {
        return !(null == str || "".equals(str.trim()));
    }

    /**
     * 判断字符串是否为空
     * @param str
     * @return
     */
    public static boolean isEmpty(String str) {
        return null == str || "".equals(str.trim());
    }

    /**
     * 检查所提供的String是否全是数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        if(isEmpty(str)) {
            return false;
        }
        Pattern pattern = Pattern.compile("[0,1,2,3,4,5,6,7,8,9,.]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    public static boolean isInteger(String str){
        if(isEmpty(str)) {
            return false;
        }
        return str.matches("[0-9]+") ;
    }

    public static boolean regexPhone(String src){
        return Pattern.matches("(^1[3|4|5|7|8]\\d{9}$)|0\\d{2}-\\d{8}|0\\d{3}-\\d{7}",src);
    }

    /**
     * 验证给定的email是否符合邮箱格式
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        boolean tag = true;
        final String pattern1 = "^([a-z0-9A-Z]+[-|_\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        final Pattern pattern = Pattern.compile(pattern1);
        final Matcher mat = pattern.matcher(email);
        if (!mat.find()) {
            tag = false;
        }
        return tag;
    }

    /**
     * 检测字符串中是否存在汉字
     * @param res
     * @return boolean
     */
    public static boolean containCN(String res){
        Pattern pattern=Pattern.compile("[\\u4e00-\\u9fa5]");
        Matcher matcher=pattern.matcher(res);
        boolean flag = matcher.find();
        return flag;
    }

 

    public static String matchPattern(String content ,String patt ,String replace){
        Pattern pattern = Pattern.compile(patt);
        Matcher matcher = pattern.matcher(content);
        if(matcher.find()){
            content = matcher.replaceAll(replace);
        }
        return content;
    }

    

    /**
     * 将字符串类型的数组 转换为 以逗号分割的字符串
     * @param stringList
     * @return
     */
    public static String array2String(Collection<String> stringList) {
        if(null == stringList) {
            return "";
        }

        StringBuffer sb = new StringBuffer();
        
        String str;
        Iterator<String> iterator = stringList.iterator();
        while(iterator.hasNext()) {
            str = iterator.next();
            if(!isEmpty(str)) {
                if(0 != sb.length()) {
                    sb.append(",");
                }
                sb.append(str);
            }
        }

        return sb.toString();
    }
    /**
     * 生成UUID
     *
     * @return
     */
    public static String genUUID() {
        return UUID.randomUUID().toString();
    }

    public static boolean isPhone(String phone){
        boolean flag = true;
        if(isEmpty(phone)){
            flag = false;
            return flag;
        }else {
            String reg = "^1[345678][0-9]{9}$";
            Pattern pattern = Pattern.compile(reg);
            flag = pattern.matcher(phone).matches();
        }
        return flag;
    }

    public static String right(String str, int len) {
        if (str == null) {
            return null;
        }
        if (len < 0) {
            return "";
        }
        if (str.length() <= len) {
            return str;
        }
        return str.substring(str.length() - len);
    }

    

    // 获取一个字符串的拼音码
    public static String getFirstLetter(String oriStr) throws Exception {
        String str = oriStr.toLowerCase();
        StringBuffer buffer = new StringBuffer();
        char ch;
        char[] temp;
        for (int i = 0; i < str.length(); i++) { // 依次处理str中每个字符
            ch = str.charAt(i);
            temp = new char[] { ch };

            //此处要注意的是，因为网上大部分是直接使用getBytes方法，根据当前平台字符集取得的字节，
            //很多win7系统都是Unicode的字符集，因此会取得三个字节的byte，这样就不会转化成功。
            //这个地方还是加上编号比较好。
            byte[] uniCode = new String(temp).getBytes("gb2312");
            if (uniCode[0] < 128 && uniCode[0] > 0) { // 非汉字
                buffer.append(temp);
            } else {
                buffer.append(convert(uniCode));
            }
        }
        return buffer.toString();
    }

    /**
     * 获取一个汉字的拼音首字母。 GB码两个字节分别减去160，转换成10进制码组合就可以得到区位码
     * 例如汉字“你”的GB码是0xC4/0xE3，分别减去0xA0（160）就是0x24/0x43
     * 0x24转成10进制就是36，0x43是67，那么它的区位码就是3667，在对照表中读音为‘n’
     */

    static char convert(byte[] bytes) {

        char result = '-';
        int secPosvalue = 0;
        int i;
        for (i = 0; i < bytes.length; i++) {
            bytes[i] -= GB_SP_DIFF;
        }
        secPosvalue = bytes[0] * 100 + bytes[1];
        for (i = 0; i < 23; i++) {
            if (secPosvalue >= secPosvalueList[i]
                    && secPosvalue < secPosvalueList[i + 1]) {
                result = firstLetter[i];
                break;
            }
        }
        return result;
    }


    /**
     * 隐藏用户名 (脱敏)
     * 默认留前面3位
     * @param name
     * @return
     */
    public static String hideName(String name) {
        return hideName(name, 3);
    }


    /**
     * 隐藏用户名
     * @param name
     * @param first
     * @return
     */
    public static String hideName(String name, int first) {
        if (null == name) {
            return null;
        }
        int len = name.length();
        if (len <= first) {
            return name + "***";
        }
        if (len == 11) {
            //手机号
            return name.substring(0, first) + "***" + name.substring(7);
        } else {
            int at = name.indexOf('@');
            if (at < 0) {
                //不是邮箱也不是手机号
                if(len>7) {
                    return name.substring(0, first) + "***" + name.substring(len-4);
                }
                return name.substring(0, first) + "***" + name.substring(first);
            } else {
                //邮箱
                if (at < first) {
                    return name.substring(0, at) + "***" + name.substring(at);
                }else {
                    return name.substring(0, first) + "***" + name.substring(at);
                }

            }
        }
    }

    /**
     *随机根据email和phone生成用户名
     * @return
     */
    public static String generateName(){
        String name = "";
        int randomType = NumberUtil.random.nextInt(max) % 2;
        switch(randomType){
            case 0://email
                name = generateNameByEmail();
                break;
            case 1://phone
                name = generateNameByPhone();
                break;
        }
        return name;
    }

    /**
     * 随机根据phone生成用户名
     * @return
     */
    public static String generateNameByPhone(){
        StringBuilder sBuilder = new StringBuilder();
        sBuilder.append(telHead[NumberUtil.random.nextInt(max) % telHead.length]);
        while (sBuilder.length() < 11) {
            sBuilder.append(NumberUtil.random.nextInt(10));
        }
        return sBuilder.toString();
    }

    /**
     * 随机根据email生成用户名
     * @return
     */
    public static String generateNameByEmail(){
        StringBuilder sBuilder = new StringBuilder();
        if(NumberUtil.random.nextInt(max)%2==0){
            sBuilder.append(firstName[NumberUtil.random.nextInt(max) % firstName.length]);
            sBuilder.append(firstLetter[NumberUtil.random.nextInt(max) % firstLetter.length]);
        }else{
            sBuilder.append(telHead[NumberUtil.random.nextInt(max) % telHead.length]);
            while (sBuilder.length() < 11) {
                sBuilder.append(NumberUtil.random.nextInt(10));
            }
        }
        sBuilder.append(emailSuffix[NumberUtil.random.nextInt(max) % emailSuffix.length]);
        return sBuilder.toString();
    }

    //生成随机数
    public static String generateRandomNum(int length){
        StringBuilder sBuilder = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sBuilder.append(NumberUtil.random.nextInt(10));
        }
        return sBuilder.toString();
    }

    //去除json中null值
    public static String jsonTrim(Object object){
        return GSON.toJson(object);
    }
    
    public static Gson GSON = new GsonBuilder()
    .setDateFormat("yyyy-MM-dd HH:mm:ss")
    .create();

    public static String nullToBlank(String str){
        return str == null?"":str;
    }
}
